<template>
  <el-dialog :title="dialogTitle" v-model="dialogVisible" fullscreen>
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" v-loading="formLoading">
      <!-- <el-row :gutter="20">
        <el-col :span="20">
          <el-form-item label="分布" prop="distribution">
            <el-radio-group v-model="formData.distribution">
              <el-radio v-for="dict in getIntDictOptions(DICT_TYPE.DISTRIBUTION_TYPE)" :key="dict.value"
                :label="dict.value">
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row> -->
      <el-row :gutter="20">
        <el-col :span="5">
          <el-form-item label="投诉日期" prop="complaintDate">
            <el-date-picker v-model="formData.complaintDate" type="date" value-format="YYYY-MM-DD"
              placeholder="选择投诉日期" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="上板日期" prop="boardtDate">
            <el-date-picker @change="boardDateChange" v-model="formData.boardtDate" type="date"
              value-format="YYYY-MM-DD" placeholder="选择上板日期" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="计划关闭日期" prop="planCloseDate">
            <el-date-picker v-model="formData.planCloseDate" type="date" disabled value-format="YYYY-MM-DD"
              placeholder="选择计划关闭日期" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="问题来源" prop="problemSource">
            <el-select v-model="formData.problemSource" placeholder="请选择问题来源">
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.PROBLEM_SOURCE)" :key="dict.value"
                :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="状态" prop="status">
            <el-select v-model="formData.status">
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.FEEDBACK_STATUS)" :key="dict.value"
                :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="问题等级" prop="problemLevel">
            <el-select v-model="formData.problemLevel" placeholder="请选择问题等级">
              <el-option v-for="dict in getStrDictOptions(DICT_TYPE.PROBLEM_LEVEL)" :key="dict.value"
                :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="客户" prop="customer">
            <el-input v-model="formData.customer" placeholder="请输入客户" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="部门" prop="deptId">
            <el-tree-select v-model="formData.deptId" :data="deptList" :props="defaultProps" check-strictly
              node-key="id" placeholder="请选择归属部门" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="提出人" prop="proposer">
            <el-select clearable filterable v-model="formData.proposer" placeholder="请选择">
              <el-option v-for="dict in userList" :key="dict.id" :label="dict.nickname" :value="dict.id" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="4">
          <el-form-item label="历时" prop="duration">
            <el-input disabled v-model="formData.duration" placeholder="" />
          </el-form-item>
        </el-col>

        <el-col :span="5">
          <el-form-item label="责任人" prop="dutyUserId">
            <el-select clearable filterable v-model="formData.dutyUserId" placeholder="请选择">
              <el-option v-for="dict in userList" :key="dict.id" :label="dict.nickname" :value="dict.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="解决成员" prop="solveUser">
            <el-select multiple clearable filterable v-model="formData.solveUser" placeholder="请选择">
              <el-option v-for="dict in userList" :key="dict.id" :label="dict.nickname" :value="dict.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="售后或0公里" prop="afterOr">
            <el-select v-model="formData.afterOr" placeholder="请选择售后或0公里">
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.AFTER_OR)" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="是否重发" prop="resend">
            <el-tooltip effect="dark" content="选择是则重新推送消息给责任人和解决小组成员" placement="top">

              <el-radio-group v-model="formData.resend" fill="#6cf">
                <el-radio-button v-for="item in getIntDictOptions(DICT_TYPE.RESEND_TYPE)" :key="item.value"
                  :value="item.value" :label="item.label" />
              </el-radio-group>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="D2:问题描述" prop="problemDescription">
            <Editor v-model="formData.problemDescription" height="250px" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="领导指示" prop="instruction">
            <Editor v-model="formData.instruction" height="250px" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="D2:到期日期" prop="expirationDateTwo">
            <el-date-picker type="date" v-model="formData.expirationDateTwo" disabled placeholder="请输入D2:到期日期" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="D3:ICA临时措施" prop="interimMeasures">
            <Editor v-model="formData.interimMeasures" height="250px" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="D4:原因分析" prop="reasonAnalysis">
            <el-tooltip effect="dark" content="参考原因:人 机 料 法 环 测 系统原因" placement="top">
              <Editor v-model="formData.reasonAnalysis" height="250px" />
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="D3:到期日期" prop="expirationDateThree">
            <el-date-picker type="date" v-model="formData.expirationDateThree" disabled placeholder="请输入D3:到期日期" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="D4:到期日期" prop="expirationDateFour">
            <el-date-picker type="date" v-model="formData.expirationDateFour" disabled placeholder="请输入D4:到期日期" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="D5:PCA永久措施 " prop="longMeasures">
            <Editor v-model="formData.longMeasures" height="250px" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="D6:PCA验证结果 " prop="verify">
            <Editor v-model="formData.verify" height="250px" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="D5:到期日期" prop="expirationDateFive">
            <el-date-picker type="date" v-model="formData.expirationDateFive" disabled placeholder="请输入D5:到期日期" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="D6:到期日期" prop="expirationDateSix">
            <el-date-picker type="date" v-model="formData.expirationDateSix" disabled placeholder="请输入D6:到期日期" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="files">
            <template #label>
              <el-tooltip effect="dark" content="程序文件、控制计划、FMEA、工艺文件是否更新" placement="top">
                <span>文件是否更新？</span>
              </el-tooltip>
            </template>
            <UploadFile :is-show-tip="false" v-model="formData.files" />
          </el-form-item>
        </el-col>
        <el-form-item label="D7:到期日期" prop="expirationDateSeven">
          <el-date-picker type="date" v-model="formData.expirationDateSeven" disabled placeholder="请输入D7:到期日期" />
        </el-form-item>
        <el-form-item label="下次汇报日期" prop="reportDate">
          <el-date-picker v-model="formData.reportDate" type="date" value-format="YYYY-MM-DD" placeholder="下次汇报日期" />
        </el-form-item>
        <el-form-item label="问题关闭日期" prop="problemCloseDate">
          <el-date-picker v-model="formData.problemCloseDate" type="date" value-format="YYYY-MM-DD"
            placeholder="问题关闭日期" />
        </el-form-item>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { FeedbackApi, Feedback } from '@/api/business/feedback'
import { dateFormatter, formatDate } from '@/utils/formatTime'
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'


/** 快捷反馈 表单 */
defineOptions({ name: 'FeedbackForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const today = new Date();
const boardtDate = formatDate(today);

// 创建一个新的日期对象用于计算 planCloseDate
const planCloseDate = new Date(today);
planCloseDate.setMonth(planCloseDate.getMonth() + 1); // 加一个月
const formattedPlanCloseDate = formatDate(planCloseDate); // 假设 formatDate 能格式化 Date 对象

const deptList = ref<Tree[]>([]) // 树形结构

const formData = ref({
  id: undefined,
  complaintDate: undefined,
  boardtDate: formatDate(new Date()),
  planCloseDate: formattedPlanCloseDate,
  status: 1,
  problemSource: undefined,
  problemLevel: undefined,
  distribution: 1,
  duration: undefined,
  customer: undefined,
  deptId: undefined,
  proposer: undefined,
  resend: 1,
  dutyUserId: [],
  solveUser: [],
  solveUserName: undefined,
  problemDescription: undefined,
  instruction: undefined,
  expirationDateTwo: formatDate(new Date()),
  interimMeasures: undefined,
  reasonAnalysis: undefined,
  expirationDateThree: formatDate(new Date(Date.now() + 1 * 24 * 60 * 60 * 1000)),
  expirationDateFour: formatDate(new Date(Date.now() + 3 * 24 * 60 * 60 * 1000)),
  longMeasures: undefined,
  verify: undefined,
  expirationDateFive: formatDate(new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)),
  expirationDateSix: formatDate(new Date(Date.now() + 10 * 24 * 60 * 60 * 1000)),
  files: [],
  expirationDateSeven: formatDate(new Date(Date.now() + 15 * 24 * 60 * 60 * 1000)),
  reportDate: undefined,
  problemCloseDate: undefined,
  afterOr: undefined
})
const formRules = reactive({
  complaintDate: [{ required: true, message: '投诉日期不能为空', trigger: 'blur' }],
  boardtDate: [{ required: true, message: '上板日期不能为空', trigger: 'blur' }],
  planCloseDate: [{ required: true, message: '计划关闭日期不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
  problemSource: [{ required: true, message: '问题来源不能为空', trigger: 'change' }],
  problemLevel: [{ required: true, message: '问题等级不能为空', trigger: 'change' }],
  distribution: [{ required: true, message: '分布不能为空', trigger: 'blur' }],
  proposer: [{ required: true, message: '提出人不能为空', trigger: 'blur' }],
  resend: [{ required: true, message: '是否重发不能为空', trigger: 'blur' }],
  dutyUserId: [{ required: true, message: '责任人不能为空', trigger: 'blur' }],
  solveUser: [{ required: true, message: '解决小组成员不能为空', trigger: 'blur' }],
  problemDescription: [{ required: true, message: 'D2:问题描述不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref


//用户列表
const userList = ref([])

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  // 加载部门树
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
  userList.value = await UserApi.getSimpleUserList()
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await FeedbackApi.getFeedback(id)
    } finally {
      formLoading.value = false
    }
  }
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const boardDateChange = (selectDate) => {
  console.log("selectDate", selectDate);

  // 1. planCloseDate = boardtDate + 1个月
  const planCloseDate = new Date(selectDate);
  planCloseDate.setMonth(planCloseDate.getMonth() + 1);
  const formattedPlanCloseDate = formatDate(planCloseDate);

  // 2. 其他 expirationDate 基于当前时间（now）偏移
  const now = new Date(); // 当前时间

  const getFutureDate = (days) => formatDate(new Date(now.getTime() + days * 24 * 60 * 60 * 1000));

  // 3. 更新 formData
  formData.value.planCloseDate = formattedPlanCloseDate;

  // 重置其他字段
  formData.value.expirationDateTwo = formData.value.boardtDate
  formData.value.expirationDateThree = getFutureDate(1);     // +1天
  formData.value.expirationDateFour = getFutureDate(3);     // +3天
  formData.value.expirationDateFive = getFutureDate(7);     // +7天
  formData.value.expirationDateSix = getFutureDate(10);    // +10天
  formData.value.expirationDateSeven = getFutureDate(15);    // +15天

};



/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as Feedback
    if (formType.value === 'create') {
      await FeedbackApi.createFeedback(data)
      message.success(t('common.createSuccess'))
    } else {
      await FeedbackApi.updateFeedback(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    complaintDate: undefined,
    boardtDate: formatDate(new Date()),
    planCloseDate: formattedPlanCloseDate,
    status: 1,
    problemSource: undefined,
    problemLevel: undefined,
    distribution: 1,
    duration: undefined,
    customer: undefined,
    deptId: undefined,
    proposer: undefined,
    resend: 1,
    dutyUserId: [],
    solveUser: [],
    solveUserName: undefined,
    problemDescription: undefined,
    instruction: undefined,
    expirationDateTwo: formatDate(new Date()),
    interimMeasures: undefined,
    reasonAnalysis: undefined,
    expirationDateThree: formatDate(new Date(Date.now() + 1 * 24 * 60 * 60 * 1000)),
    expirationDateFour: formatDate(new Date(Date.now() + 3 * 24 * 60 * 60 * 1000)),
    longMeasures: undefined,
    verify: undefined,
    expirationDateFive: formatDate(new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)),
    expirationDateSix: formatDate(new Date(Date.now() + 10 * 24 * 60 * 60 * 1000)),
    files: [],
    expirationDateSeven: formatDate(new Date(Date.now() + 15 * 24 * 60 * 60 * 1000)),
    reportDate: undefined,
    problemCloseDate: undefined,
    afterOr: undefined
  }
  formRef.value?.resetFields()
}
</script>
